package com.enlf.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.enlf.dto.Result;
import com.enlf.entity.ShopType;
import com.enlf.mapper.ShopTypeMapper;
import com.enlf.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.enlf.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author renge
 * @since 2023-9-11
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        /*
         * string的形式纯入redis*/

        //1.从缓存中查询是否有店铺类型信息
        String key = SHOPSTR_TYPE_KEY + "list";
        String shopType = stringRedisTemplate.opsForValue().get(key);
        //2.有 返回
        if (StrUtil.isNotBlank(shopType)){
            List<ShopType> shopTypes = JSONUtil.toList(shopType, ShopType.class);
            return Result.ok(shopTypes);
        }
        //3.没有 查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //4.查不到报404
        if (shopTypes.isEmpty()){
            return Result.fail("店铺不存在!");
        }
        //5.生成缓存存储
        String cache = JSONUtil.toJsonStr(shopTypes);
        stringRedisTemplate.opsForValue().set(key,cache);
        //6.返回商铺信息
        return Result.ok(shopTypes);
    }
    /**
     * 查询店铺类型列表 将店铺类型缓存到redis中
     * @return
     */
  /*  @Override
    public Result queryList() {

        //1.从缓存中查询是否有店铺类型信息
//        List<String> list = stringRedisTemplate.opsForList().range(key, 0, -1);
        String key = SHOP_TYPE_KEY + "list";
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2.有 返回
        if (!shopTypeList.isEmpty()){
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeList.toString(), ShopType.class);
            return Result.ok(shopTypes);
        }
        //3.没有 查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //查数据库查不到 报404
        if (shopTypes.isEmpty()){
            return Result.fail("店铺不存在");
        }
        //4.生成缓存存储
        shopTypeList = JSONUtil.toList(new JSONArray(shopTypes), String.class);
        stringRedisTemplate.opsForList().rightPushAll(key,shopTypeList);
        //5.返回商铺信息
        return Result.ok(shopTypes);
    }*/
}
